package com.radioapp.liaoliaobao.view.dialog.more_select;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jaydenxiao.common.commonutils.ToastUitl;
import com.radioapp.liaoliaobao.R;
import com.radioapp.liaoliaobao.view.flowreclyclerview.FlowLayoutManager;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 功能：底部弹窗（多选或者单选）
 * 描述
 * Created by yue on 2019-07-24
 */
public class MoreSelectDialog<T> extends DialogFragment {

    @BindView(R.id.tv_cancelBtn)
    TextView tvCancelBtn;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_selectedNumber)
    TextView tvSelectedNumber;
    @BindView(R.id.titleLayout)
    RelativeLayout titleLayout;
    @BindView(R.id.confirmBtn)
    TextView confirmBtn;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.mRecycleView)
    RecyclerView mRecycleView;
    private Unbinder mUnbinder;
    private MoreSelectAdapter moreSelectAdapter;
    private String title;
    private int mTitleTextColor = -1;
    private String confirmText;
    private int mConfirmTextColor = -1;
    private String cancelText;
    private int mCancelTextColor = -1;
    private int maxSelect = -1;
    private List<T> list;
    private Set<T> selectList = new HashSet<>();
    private OnConfirmClickListener onConfirmClickListener;


    public interface OnConfirmClickListener<T> {
        void onClick(Set<T> selectLists);
    }


    public static MoreSelectDialog newInstance(List items, OnConfirmClickListener mListener) {

        MoreSelectDialog fragment = new MoreSelectDialog();
        fragment.setOnConfirmClickListener(mListener);
        fragment.setData(items);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //设置style
        setStyle(DialogFragment.STYLE_NORMAL, R.style.BottomDialog);

    }


    @Override
    public void onStart() {
        super.onStart();
        //设置 dialog 的宽高
        getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        //设置 dialog 的背景为 null
        getDialog().getWindow().setBackgroundDrawable(null);

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        //去除标题栏
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);


        Window window = getDialog().getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.gravity = Gravity.BOTTOM; //底部
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(lp);

        return createView(inflater, container);
    }


    //重写此方法，设置布局文件
    protected View createView(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.more_dialog, container, false);
        mUnbinder = ButterKnife.bind(this, view);
        initView();
        return view;
    }


    private void initView() {
        FlowLayoutManager flowLayoutManager = new FlowLayoutManager();
        //设置每一个item间距
        //  SpaceItemDecoration spaceItemDecoration = new SpaceItemDecoration(DisplayUtil.dip2px(5));
        mRecycleView.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
        // mRecycleView.addItemDecoration(spaceItemDecoration);
        // flowLayoutManager.setAutoMeasureEnabled(true);
        mRecycleView.setHasFixedSize(true);
        mRecycleView.setNestedScrollingEnabled(false);

        moreSelectAdapter = new MoreSelectAdapter();
        mRecycleView.setAdapter(moreSelectAdapter);
        moreSelectAdapter.setNewData(list);
        moreSelectAdapter.initStates(list);
        if (!TextUtils.isEmpty(title))
            tvTitle.setText(title);
        if (mTitleTextColor != -1)
            tvTitle.setTextColor(mTitleTextColor);
        if (!TextUtils.isEmpty(confirmText))
            confirmBtn.setText(confirmText);
        if (mConfirmTextColor != -1)
            confirmBtn.setTextColor(mConfirmTextColor);
        if (!TextUtils.isEmpty(confirmText))
            tvCancelBtn.setText(confirmText);
        if (mCancelTextColor != -1)
            tvCancelBtn.setTextColor(mCancelTextColor);


        moreSelectAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.root_view) {
                    moreSelectAdapter.getSelectStates()[position] = !moreSelectAdapter.getSelectStates()[position];
                    if (tvSelectedNumber != null) {
                        int size = getSelectedPosition().size();

                        if(size>maxSelect){
                            ToastUitl.showLong("最多能选择"+maxSelect+"个");
                            moreSelectAdapter.getSelectStates()[position]=false;
                            return;
                        }
                        //设置个数
                        tvSelectedNumber.setText(size+ "");
                        tvSelectedNumber.setVisibility(size == 0 ? View.GONE : View.VISIBLE);
                        moreSelectAdapter.notifyDataSetChanged();
                    }

                }
            }
        });
    }


    /**
     * get the indexes in an array which you had selected
     *
     * @return
     */
    public ArrayList<Integer> getSelectedPosition() {
        ArrayList<Integer> result = new ArrayList<>();
        if (moreSelectAdapter.getSelectStates() == null) return result;
        for (int i = 0; i < moreSelectAdapter.getSelectStates().length; i++) {
            if (moreSelectAdapter.getSelectStates()[i]) {
                result.add(i);
            }
        }
        return result;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mUnbinder.unbind();
    }

    @OnClick({R.id.tv_cancelBtn, R.id.confirmBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_cancelBtn:
                dismiss();
                break;
            case R.id.confirmBtn:
                selectList.clear();
                for (int i = 0; i < moreSelectAdapter.getSelectStates().length; i++) {
                    if (moreSelectAdapter.getSelectStates()[i]) {
                        selectList.add((T) moreSelectAdapter.getData().get(i));
                    }
                }

                if (onConfirmClickListener != null) {
                    onConfirmClickListener.onClick(selectList);
                }
                dismiss();
                break;
        }
    }


    /**
     * set title
     *
     * @param title
     * @return
     */
    public MoreSelectDialog setTitle(String title) {
        this.title = title;

        return this;
    }

    /**
     * set confirm button text
     *
     * @param str
     * @return
     */
    public MoreSelectDialog setConfirm(String str) {
        this.confirmText = str;

        return this;
    }

    public MoreSelectDialog setMaxSelect(int max) {
        this.maxSelect = max;
        return this;
    }

    /**
     * set cacel button text
     *
     * @param str
     * @return
     */
    public MoreSelectDialog setCancel(String str) {
        this.cancelText = str;

        return this;
    }

    /**
     * set title's text color
     *
     * @param color
     * @return
     */
    public MoreSelectDialog setTitleTextColor(int color) {
        this.mTitleTextColor = color;

        return this;
    }

    /**
     * set confirm button's text color
     *
     * @param color
     * @return
     */
    public MoreSelectDialog setConfirmTextColor(int color) {
        this.mConfirmTextColor = color;

        return this;
    }

    /**
     * set cancel button's text color
     *
     * @param color
     * @return
     */
    public MoreSelectDialog setCancelTextColor(int color) {
        this.mCancelTextColor = color;

        return this;
    }


    public MoreSelectDialog setData(List<T> list) {
        this.list = list;

        return this;
    }

    public MoreSelectDialog setOnConfirmClickListener(OnConfirmClickListener onConfirmClickListener) {
        this.onConfirmClickListener = onConfirmClickListener;
        return this;
    }


}
